package com.smartguard.util;

import java.lang.reflect.Field;
import java.util.Date;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

public class PojoUtil {
	
	/**
	 * 将pojo类转换为DBObject
	 * @param pojo
	 * @return DBObject
	 */
	public static DBObject Pojo2DBObject(Object pojo){
		DBObject dbObject = new BasicDBObject();
		
		if(pojo == null) {
			return dbObject;
		}
		
		Field[] fields = pojo.getClass().getDeclaredFields();
		int nullCount = 0;
		for(Field field: fields){
			//得到原来的属性访问标记，用于复原
			boolean flag = field.isAccessible();
			//设置属性可访问
			field.setAccessible(true);	
			Object valueObj = null;
			try {
				valueObj = field.get(pojo);
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
			
			//如果为空则不需存入
			if(null == valueObj) {
				nullCount++;
				continue;
			}
			
			//得到属性名
			String fieldName = field.getName();
			
			//往dbobject里put
			dbObject.put(fieldName, valueObj);
			
			//还原访问权限
			field.setAccessible(flag);
		}
		//如果属性全部为空，则设为空
		if(nullCount == fields.length)
			dbObject = null;
		
		return dbObject;
	}
	
	/**
	 * 将DBObject转换位pojo
	 * @param dbObject 
	 * @param clazz 目标pojo类
	 * @return
	 */
	public static <T> T DBObject2Pojo(DBObject dbObject, Class<T> clazz){
		T pojo = null;
		if(dbObject == null) {
			return pojo;
		}
		
		try {
			pojo = clazz.newInstance();
		} catch (InstantiationException | IllegalAccessException e1) {
			e1.printStackTrace();
		}
		
		Field[] fields = clazz.getDeclaredFields();
		
		for(Field field: fields){
			//得到原来的属性访问标记，用于复原
			boolean flag = field.isAccessible();
			//设置属性可访问
			field.setAccessible(true);	
			
			//得到属性名
			String fieldName = field.getName();
			Object valueObj = dbObject.get(fieldName);
			try {
				//System.out.println(field.getType()+":"+valueObj.getClass());
				field.set(pojo, valueObj);
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
			
			field.setAccessible(flag);
		}
		
		return pojo;
	}
	
	//测试
	/*
	public static void main(String[] args){
		PojoDBObjectTransfer a = new PojoDBObjectTransfer();
		DBObject obj = Pojo2DBObject(new User());
		System.out.println(obj.get("name"));
		
		DBObject dbo = new BasicDBObject();
		dbo.put("name", "李清");
		dbo.put("age", 18);
		dbo.put("date", new Date());
		User user = DBObject2Pojo(dbo, User.class);
		System.out.println(user.getDate());
	}
	*/
	
}
